R and D3

Jan-Philipp Kolb

7 Februar 2017

JavaScript - Data-Driven Documents

gigvis

install.packages("ggvis")
library("ggvis")
library(dplyr)

Kochbuch für ggvis

mtcars %>% ggvis(~wt, ~mpg) %>% layer_points()

Plots mit Gruppierung

mtcars %>% 
  ggvis(~wt, ~mpg, fill = ~factor(cyl)) %>% 
  layer_points() %>% 
  group_by(cyl) %>% 
  layer_model_predictions(model = "lm")

googleVis

install.packages("googleVis")
library(googleVis)
df <- data.frame(year=1:11, x=1:11,
                 x.scope=c(rep(TRUE, 8), rep(FALSE, 3)),
                 y=11:1, y.html.tooltip=LETTERS[11:1],                 
                 y.certainty=c(rep(TRUE, 5), rep(FALSE, 6)),
                 y.emphasis=c(rep(FALSE, 4), rep(TRUE, 7)))
plot(
  gvisScatterChart(df,options=list(lineWidth=2))
)

Click me

install.packages("devtools")
library(devtools)

install_github("clickme", "nachocab")
library(clickme)

# simple
clickme("points", 1:10)

# fancy
n <- 500
clickme("points",
    x = rbeta(n, 1, 10), y = rbeta(n, 1, 10),
    names = sample(letters, n, r = T),
    color_groups = sample(LETTERS[1:3], n, r = T),
    title = "Zoom Search Hover Click")

d3Network

install.packages("d3Network")
library(d3Network)
Source <- c("A", "A", "A", "A", "B", "B", "C", "C", "D")
Target <- c("B", "C", "D", "J", "E", "F", "G", "H", "I")
NetworkData <- data.frame(Source, Target)
d3SimpleNetwork(NetworkData, width = 400, height = 250)
## 
##         <!DOCTYPE html>
##         <meta charset="utf-8">
##         <body> 
##  <style>
## .link {
## stroke: #666;
## opacity: 0.6;
## stroke-width: 1.5px;
## }
## .node circle {
## stroke: #fff;
## opacity: 0.6;
## stroke-width: 1.5px;
## }
## text {
## font: 7px serif;
## opacity: 0.6;
## pointer-events: none;
## }
## </style>
## 
## <script src=http://d3js.org/d3.v3.min.js></script>
## 
## <script> 
##  var links = [ { "source" : "A", "target" : "B" }, { "source" : "A", "target" : "C" }, { "source" : "A", "target" : "D" }, { "source" : "A", "target" : "J" }, { "source" : "B", "target" : "E" }, { "source" : "B", "target" : "F" }, { "source" : "C", "target" : "G" }, { "source" : "C", "target" : "H" }, { "source" : "D", "target" : "I" } ] ; 
##  var nodes = {}
## 
## // Compute the distinct nodes from the links.
## links.forEach(function(link) {
## link.source = nodes[link.source] ||
## (nodes[link.source] = {name: link.source});
## link.target = nodes[link.target] ||
## (nodes[link.target] = {name: link.target});
## link.value = +link.value;
## });
## 
## var width = 400
## height = 250;
## 
## var force = d3.layout.force()
## .nodes(d3.values(nodes))
## .links(links)
## .size([width, height])
## .linkDistance(50)
## .charge(-200)
## .on("tick", tick)
## .start();
## 
## var svg = d3.select("body").append("svg")
## .attr("width", width)
## .attr("height", height);
## 
## var link = svg.selectAll(".link")
## .data(force.links())
## .enter().append("line")
## .attr("class", "link");
## 
## var node = svg.selectAll(".node")
## .data(force.nodes())
## .enter().append("g")
## .attr("class", "node")
## .on("mouseover", mouseover)
## .on("mouseout", mouseout)
## .on("click", click)
## .on("dblclick", dblclick)
## .call(force.drag);
## 
## node.append("circle")
## .attr("r", 8)
## .style("fill", "#3182bd");
## 
## node.append("text")
## .attr("x", 12)
## .attr("dy", ".35em")
## .style("fill", "#3182bd")
## .text(function(d) { return d.name; });
## 
## function tick() {
## link
## .attr("x1", function(d) { return d.source.x; })
## .attr("y1", function(d) { return d.source.y; })
## .attr("x2", function(d) { return d.target.x; })
## .attr("y2", function(d) { return d.target.y; });
## 
## node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
## }
## 
## function mouseover() {
## d3.select(this).select("circle").transition()
## .duration(750)
## .attr("r", 16);
## }
## 
## function mouseout() {
## d3.select(this).select("circle").transition()
## .duration(750)
## .attr("r", 8);
## }
## // action to take on mouse click
## function click() {
## d3.select(this).select("text").transition()
## .duration(750)
## .attr("x", 22)
## .style("stroke-width", ".5px")
## .style("opacity", 1)
## .style("fill", "#E34A33")
## .style("font", "17.5px serif");
## d3.select(this).select("circle").transition()
## .duration(750)
## .style("fill", "#E34A33")
## .attr("r", 16)
## }
## 
## // action to take on mouse double click
## function dblclick() {
## d3.select(this).select("circle").transition()
## .duration(750)
## .attr("r", 6)
## .style("fill", "#E34A33");
## d3.select(this).select("text").transition()
## .duration(750)
## .attr("x", 12)
## .style("stroke", "none")
## .style("fill", "#E34A33")
## .style("stroke", "none")
## .style("opacity", 0.6)
## .style("font", "7px serif");
## }
## 
## </script>
##  </body>
sink("FirstNetwork.js") 

writeLines(d3SimpleNetwork(NetworkData), fileConn)
unlink("FirstNetwork.js")

Rook

install.packages("Rook")

HTML widgets in R

library(dygraphs)
dygraph(nhtemp, main = "New Haven Temperatures") %>% 
  dyRangeSelector(dateWindow = c("1920-01-01", "1960-01-01"))

Combo Chart

library(googleVis)
op <- options(gvis.plot.tag = "chart")
## Add the mean
CityPopularity$Mean=mean(CityPopularity$Popularity)
CC <- gvisComboChart(CityPopularity, xvar='City',
          yvar=c('Mean', 'Popularity'),
          options=list(seriesType='bars',
                       width=450, height=300,
                       title='City Popularity',
                       series='{0: {type:\"line\"}}'))
plot(CC)
## <!-- ComboChart generated in R 3.3.2 by googleVis 0.6.2 package -->
## <!-- Fri May 05 16:20:44 2017 -->
## 
## 
## <!-- jsHeader -->
## <script type="text/javascript">
##  
## // jsData 
## function gvisDataComboChartID265434c22086 () {
## var data = new google.visualization.DataTable();
## var datajson =
## [
##  [
## "New York",
## 450,
## 200
## ],
## [
## "Boston",
## 450,
## 300
## ],
## [
## "Miami",
## 450,
## 400
## ],
## [
## "Chicago",
## 450,
## 500
## ],
## [
## "Los Angeles",
## 450,
## 600
## ],
## [
## "Houston",
## 450,
## 700
## ] 
## ];
## data.addColumn('string','City');
## data.addColumn('number','Mean');
## data.addColumn('number','Popularity');
## data.addRows(datajson);
## return(data);
## }
##  
## // jsDrawChart
## function drawChartComboChartID265434c22086() {
## var data = gvisDataComboChartID265434c22086();
## var options = {};
## options["allowHtml"] = true;
## options["seriesType"] = "bars";
## options["width"] = 450;
## options["height"] = 300;
## options["title"] = "City Popularity";
## options["series"] = {0: {type:"line"}};
## 
## 
##     var chart = new google.visualization.ComboChart(
##     document.getElementById('ComboChartID265434c22086')
##     );
##     chart.draw(data,options);
##     
## 
## }
##   
##  
## // jsDisplayChart
## (function() {
## var pkgs = window.__gvisPackages = window.__gvisPackages || [];
## var callbacks = window.__gvisCallbacks = window.__gvisCallbacks || [];
## var chartid = "corechart";
##   
## // Manually see if chartid is in pkgs (not all browsers support Array.indexOf)
## var i, newPackage = true;
## for (i = 0; newPackage && i < pkgs.length; i++) {
## if (pkgs[i] === chartid)
## newPackage = false;
## }
## if (newPackage)
##   pkgs.push(chartid);
##   
## // Add the drawChart function to the global list of callbacks
## callbacks.push(drawChartComboChartID265434c22086);
## })();
## function displayChartComboChartID265434c22086() {
##   var pkgs = window.__gvisPackages = window.__gvisPackages || [];
##   var callbacks = window.__gvisCallbacks = window.__gvisCallbacks || [];
##   window.clearTimeout(window.__gvisLoad);
##   // The timeout is set to 100 because otherwise the container div we are
##   // targeting might not be part of the document yet
##   window.__gvisLoad = setTimeout(function() {
##   var pkgCount = pkgs.length;
##   google.load("visualization", "1", { packages:pkgs, callback: function() {
##   if (pkgCount != pkgs.length) {
##   // Race condition where another setTimeout call snuck in after us; if
##   // that call added a package, we must not shift its callback
##   return;
## }
## while (callbacks.length > 0)
## callbacks.shift()();
## } });
## }, 100);
## }
##  
## // jsFooter
## </script>
##  
## <!-- jsChart -->  
## <script type="text/javascript" src="https://www.google.com/jsapi?callback=displayChartComboChartID265434c22086"></script>
##  
## <!-- divChart -->
##   
## <div id="ComboChartID265434c22086" 
##   style="width: 450; height: 300;">
## </div>
install.packages("threejs")
# install.packages("threejs")
library(threejs)
z <- seq(-10, 10, 0.01)
x <- cos(z)
y <- sin(z)
scatterplot3js(x,y,z, color=rainbow(length(z)))